import axios from "axios"
import type { Result } from "@/types/common"
import type { AxiosRequestConfig } from "axios"

const instance = axios.create({
  baseURL: "http://xxx",
  timeout: 10000,
  withCredentials: true
})

instance.interceptors.request.use(
  (config) => {
    return config
  },
  (err) => {
    return err
  }
)

instance.interceptors.response.use(
  (res) => {
    const data = res.data

    return data
  },
  (err) => {
    return err
  }
)

function request<T>(config: AxiosRequestConfig) {
  return new Promise<Result<T>>((resolve, reject) => {
    instance
      .request<any, Result<T>>(config)
      .then((res) => resolve(res))
      .catch((err) => reject(err))
  })
}

function get<T = any>(config: AxiosRequestConfig) {
  return request<T>({ ...config, method: "GET" })
}

function post<T = any>(config: AxiosRequestConfig) {
  return request<T>({ ...config, method: "POST" })
}

export { get, post }
